package com.zhhh.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParser;
import com.wordnik.swagger.annotations.ApiOperation;
import com.zhhh.config.ResultStatus;
import com.zhhh.domain.BGenerator;
import com.zhhh.domain.BMode;
import com.zhhh.domain.BModeControl;
import com.zhhh.domain.BModeEm;
import com.zhhh.domain.BModeOper;
import com.zhhh.domain.BRoleModeOper;
import com.zhhh.model.ResultModel;
import com.zhhh.repository.BaseNativeSqlRepository;
import com.zhhh.repository.BaseRepositoryImpl;
import com.zhhh.repository.GeneratorRepository;
import com.zhhh.repository.ModeControlRepository;
import com.zhhh.repository.ModeEmRepository;
import com.zhhh.repository.ModeOperRepository;
import com.zhhh.repository.ModeRepository;
import com.zhhh.repository.SqlDao;
import com.zhhh.repository.SqlRepository;
import com.zhhh.utils.CodeUtil;
import com.zhhh.utils.GenUtils;

@RestController
@RequestMapping("/Generator")
public class GeneratorController {

	@Autowired
	private GeneratorRepository generatorRepository;

	@Autowired
	private ModeRepository modeRepository;

	@Autowired
	private ModeControlRepository modeControlRepository;

	@Autowired
	private ModeOperRepository modeOperRepository;

	@Autowired
	private ModeEmRepository modeEmRepository;

	@Autowired
	private SqlDao baseRepository;

	@RequestMapping(value = "/generateCodeSql", method = RequestMethod.POST)
	@ApiOperation(value = "SQL字段预览")
	public ResponseEntity<ResultModel> generateCodeSql(@RequestParam String sql, HttpServletResponse response)
			throws IOException {
		List<Map<String, String>> columnsInfo = baseRepository.createTable(sql);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		// 生成代码
		// GenUtils.generatorCode("testTable", columnsInfo, zip);
		return new ResponseEntity<>(ResultModel.ok(columnsInfo), HttpStatus.OK);
	}

	@RequestMapping(value = "/generateCodeJson", method = RequestMethod.POST)
	@ApiOperation(value = "代码生成")
	public ResponseEntity<ResultModel> generateCodeJson(@RequestParam String json, HttpServletResponse response)
			throws IOException {
		JSONObject jo = (JSONObject) JSONObject.parse(json);
		String fname = jo.getString("fname");
		String furl = jo.getString("furl");
		JSONArray selectRows = jo.getJSONArray("selectRows");
		JSONArray checkids = jo.getJSONArray("checkids");
		JSONObject modeJo = jo.getJSONObject("mode");
		JSONObject ctrlJo = jo.getJSONObject("ctrl");
		List<Map> columnsInfo = JSON.parseArray(selectRows.toJSONString(), Map.class);

		String pattern = "^[a-zA-Z]:(((\\\\(?! )[^/:*?<>\\\"\"|\\\\]+)+\\\\?)|(\\\\)?)\\s*$";
		boolean isMatch = Pattern.matches(pattern, furl);
		if (isMatch) {

		} else {
			Map<String, Object> data = new HashMap<>();
			data.put("Exception", "路径不合法");
			return new ResponseEntity<>(ResultModel.error(ResultStatus.SYS_EXCEPTION, data), HttpStatus.OK);
		}
		String modeCode = CodeUtil.createUUID();
		// 生成代码
		boolean flag = GenUtils.generatorCode(fname, columnsInfo, checkids, furl, modeCode);
		if (flag) {
			Set<BMode> insertBModes = new HashSet<BMode>();
			Set<BModeControl> insertBModeControls = new HashSet<BModeControl>();
			Set<BModeOper> insertBModeOpers = new HashSet<BModeOper>();
			Set<BModeEm> insertBModeEms = new HashSet<BModeEm>();

			String ctrlId = CodeUtil.createUUID();
			BMode mode = new BMode();
			mode.setModeCode(modeCode);
			mode.setModeDesc(modeJo.getString("modeDesc"));
			mode.setModeName(modeJo.getString("modeName"));
			mode.setUrl(modeJo.getString("url"));
			mode.setVer(modeJo.getInteger("ver"));
			// modeRepository.save(mode);
			insertBModes.add(mode);
			BModeControl modeControl = new BModeControl();
			modeControl.setCtrlId(ctrlId);
			modeControl.setCtrlText(ctrlJo.getString("ctrlText"));
			modeControl.setDataId(ctrlJo.getString("dataId"));
			modeControl.setIfFtp(ctrlJo.getInteger("ifFtp"));
			modeControl.setModeCode(modeCode);
			modeControl.setReportUrl(ctrlJo.getString("reportUrl"));
			// modeControlRepository.save(modeControl);
			insertBModeControls.add(modeControl);
			for (int i = 0; i < checkids.size(); i++) {
				BModeOper modeOper = new BModeOper();
				String operId = CodeUtil.createUUID();
				modeOper.setCtrlCode(ctrlId);
				modeOper.setOperEvent(checkids.get(i).toString());
				modeOper.setOperId(operId);
				modeOper.setOperText(checkids.get(i).toString());
				// modeOperRepository.save(modeOper);
				insertBModeOpers.add(modeOper);
			}
			for (Map<String, String> column : columnsInfo) {
				BModeEm modeEm = new BModeEm();
				String emId = CodeUtil.createUUID();
				modeEm.setCtrlCode(ctrlId);
				modeEm.setEmId(emId);
				modeEm.setEmText(column.get("columnName"));
				modeEm.setTextDesc(column.get("columnComment"));
				// modeEmRepository.save(modeEm);
				insertBModeEms.add(modeEm);
			}

			modeRepository.saveAll(insertBModes);
			modeControlRepository.saveAll(insertBModeControls);
			modeOperRepository.saveAll(insertBModeOpers);
			modeEmRepository.saveAll(insertBModeEms);

		}
		return new ResponseEntity<>(ResultModel.ok("代码生成成功"), HttpStatus.OK);
	}

	@RequestMapping(value = "/previewSql", method = RequestMethod.POST)
	@ApiOperation(value = "预览SQL语句")
	public ResponseEntity<ResultModel> previewSql(@RequestParam String sql, HttpServletResponse response)
			throws IOException {
		List<Map> list = baseRepository.listBySQL(sql);
		List<Map<String, String>> columnsInfo = baseRepository.createTable(sql);
		JSONObject jo = new JSONObject();
		jo.put("datalist", list);
		jo.put("fieldlist", columnsInfo);
		return new ResponseEntity<>(ResultModel.ok(jo), HttpStatus.OK);
	}

	@RequestMapping(value = "/queryGeneratorAll", method = RequestMethod.POST)
	@ApiOperation(value = "查询所有代码生成规则")
	public ResponseEntity<List<BGenerator>> queryGeneratorAll() {
		List<BGenerator> findAll = (List<BGenerator>) generatorRepository.findAll();

		return new ResponseEntity<>(findAll, HttpStatus.OK);
	}

	@RequestMapping(value = "/deleteGenerator", method = RequestMethod.POST)
	@ApiOperation(value = "删除代码生成规则")
	public ResponseEntity<ResultModel> deleteGenerator(@RequestParam Integer id) {
		// generatorRepository.delete(id);
		generatorRepository.deleteById(id);
		List<BGenerator> findAll = (List<BGenerator>) generatorRepository.findAll();
		return new ResponseEntity<>(ResultModel.ok(findAll), HttpStatus.OK);
	}

	@RequestMapping(value = "/updateGenerator", method = RequestMethod.POST)
	@ApiOperation(value = "增加或者修改模块")
	public ResponseEntity<ResultModel> updateGenerator(@ModelAttribute("bGenerator") BGenerator bGenerator) {
		generatorRepository.save(bGenerator);
		List<BGenerator> findAll = (List<BGenerator>) generatorRepository.findAll();
		return new ResponseEntity<>(ResultModel.ok(findAll), HttpStatus.OK);
	}

}
